package com
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	public class BogFile
	{
		private var _file:File;
		private var _filteType:String;
		private var _loader:URLLoader;
		
		public var onErroHandle:Function;
		public var onComplete:Function;
		
		public function BogFile()
		{
			_file =  File.applicationDirectory;	
		}
		
		public function browseForOpen(tilte:String,fileter:Array,type:String=URLLoaderDataFormat.BINARY):void
		{
			_filteType = type;
			_file.browseForOpen(tilte,fileter);
			_file.addEventListener(Event.SELECT,onFileSelectedHandle);
		}
		
		private function onFileSelectedHandle(event:Event):void
		{
			_file.removeEventListener(Event.SELECT,	onFileSelectedHandle);
			
			_loader = new URLLoader();
			_loader.dataFormat = _filteType;
			_loader.addEventListener(IOErrorEvent.IO_ERROR,onIOErrorHandle);
			_loader.addEventListener(Event.COMPLETE,onFileLoadedLoadedHandle);
			_loader.load(new URLRequest(_file.nativePath));
		}
		
		private function onIOErrorHandle(event:IOErrorEvent):void
		{
			destroyEvents();
			if(onErroHandle!=null){
				onErroHandle(event.errorID);
			}
		}
		
		private function onFileLoadedLoadedHandle(event:Event):void
		{
			destroyEvents();
			
			var content:* = _loader.data;
			if(content is ByteArray){
				if(((content as ByteArray)[0]==120)&&((content as ByteArray)[1]==156)){
					(content as ByteArray).uncompress();
				}
			}
			
			if(onComplete!=null){
				onComplete(content);
			}
		}
		
		private function destroyEvents():void
		{
			_loader.removeEventListener(Event.COMPLETE,onFileLoadedLoadedHandle);
			_loader.removeEventListener(IOErrorEvent.IO_ERROR,onIOErrorHandle);
			
		}
	}
}